package com.qf.agro.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.agro.mapper.ModelMapper;
import com.qf.agro.pojo.SysModule;
import com.qf.agro.service.sys.ModelService;
import io.swagger.v3.oas.annotations.servers.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 千锋健哥
 */
@Service
public class ModelServieImpl implements ModelService {

    @Autowired
    private ModelMapper modelMapper;

    //spring data redis
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<SysModule> findMenuList(Long userId) {
        List<SysModule> list = modelMapper.findListByUserId(userId);
        return list;
    }

    @Override
    public List<SysModule> findMenuAll(Long userId) {
        //1. 根据当前登录用户, 到redis中获取菜单.
        List<SysModule> parentList = (List<SysModule>)redisTemplate.opsForValue().get(String.valueOf(userId));

        //2. 判断如果redis中有这个用户的菜单, 直接返回显示
        if (parentList != null && parentList.size() > 0) {
            return parentList;
        }

        //3. 如果redis中没有这个用户的菜单, 则到数据库查询
        parentList = modelMapper.findParentListByUserId(userId);

        //遍历父菜单集合
        if (parentList != null) {
            for (SysModule sysModule : parentList) {
                QueryWrapper<SysModule> childQueryWrapper = new QueryWrapper<>();
                //根据父id, 查子菜单集合
                childQueryWrapper.eq("parent_id", sysModule.getId());
                List<SysModule> childList = modelMapper.selectList(childQueryWrapper);
                //将子菜单集合放入父菜单
                sysModule.setChildren(childList);
            }
        }

        return parentList;
    }

}
